/*
 * @Description: 
 * @version: 
 * @Author: 周曾辉
 * @Date: 2020-04-14 23:48:03
 * @LastEditors: CoderXZ
 * @LastEditTime: 2020-05-28 23:26:18
 */

import Base64 from "../Utils/Base64";
import CheckPointMgr from "../Data/DataMgr/CheckPointMgr";


interface UserInfo{
    nickName:string;
    sex:number;
    headIcon:string;
    province:string;
}
export default class UserData {

    private static m_instance:UserData = null;

    private m_killEnemyNum:number = 0;

    private m_checkPointNum:number = 1;

    private m_userInfo:UserInfo = null;

    public static getInstance():UserData{
        if(!this.m_instance){
            this.m_instance = new UserData();
            this.m_instance.init();
        }

        return this.m_instance;
    }

    private init(){
        this.initData();
        this.loadData();
    }

    private static setUserData(obj:any){
        let m_instance = Object.assign({},obj);

        for(let key in m_instance){
            if(m_instance.hasOwnProperty(key)){
                this[key] = m_instance[key];
                this.m_instance[key] = m_instance[key];
            }
        }
    }

    private initData(){
        this.m_checkPointNum = 1;
        this.m_killEnemyNum = 0;
        this.saveLocalData();
    }

    private loadData(){
        let userInfoStr = cc.sys.localStorage.getItem("UserInfo");
        cc.log("userInfoStr:" + userInfoStr);
        if(!userInfoStr){
            return;
        }
        userInfoStr = Base64.decode(userInfoStr);
        // cc.log("getItem str:" + userInfoStr);
        UserData.setUserData(JSON.parse(userInfoStr));
    }

    private saveLocalData():void{
        let str = JSON.stringify(this);
        // cc.log("saveLocalData str:" + str);
        cc.sys.localStorage.setItem("UserInfo",Base64.encode(str));


        let userInfoStr = cc.sys.localStorage.getItem("UserInfo");
        userInfoStr = Base64.decode(userInfoStr);
        // cc.log("getItem str:" + userInfoStr);
    }

    public addKillEnemyNum():void{
        this.m_killEnemyNum++;
        // this.saveLocalData();
    }

    public getKillEnemyNum():number{
        return this.m_killEnemyNum;
    }

    public addCheckPointNum(){
        this.m_checkPointNum++;
        CheckPointMgr.getInstance().setCurCheckPointNum(this.m_checkPointNum);
        this.saveLocalData();
    }

    public getCheckPointNum(){
        return this.m_checkPointNum;
    }

    public setUserInfo(userInfo:UserInfo){
        this.m_userInfo.headIcon = userInfo.headIcon;
        this.m_userInfo.nickName = userInfo.headIcon;
        this.m_userInfo.sex = userInfo.sex;
        this.m_userInfo.province = userInfo.province;
    }

    public getNickName():string{
        return this.m_userInfo.nickName;
    }

    public getHeadIcon():string{
        return this.m_userInfo.headIcon;
    }
}
